#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tornado.web import RequestHandler
import pymongo
import re
import render
import codecs
from _base import BaseHandler
import datetime
import sys
sys.path.insert(0,'/home/leeray/workspaces/Python/wanalytics/')
from Tools import getPid
from Tools import connectMySQL 
import json
from util import cache, settings
import _clientCache as clientcache


class WapClient(BaseHandler):
    def get(self): 
        os_json = clientcache.getOS()
        
        pidtype_json = clientcache.getPidType()
        
        _time = self.get_argument('staDate', '2011/11/01').strip()
        _pd = self.get_argument('pd','').strip()
        
        st_time = datetime.datetime.strptime(_time, '%Y/%m/%d')
        if not _pd:
            ed_time = datetime.datetime.now()
            delta = ed_time - st_time 
            _pd =  abs(delta.days)
        _pd = int(_pd)
        et_time = st_time + datetime.timedelta(days=_pd)
        st_datestr = st_time.strftime('%Y%m%d')
        et_datestr = et_time.strftime('%Y%m%d')
        
        all_data = []
        results = {}
        os_data = []
        
        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        sql = "SELECT date, os_id, pid_type, sum(pv), sum(uv), sum(vv), sum(newuser), sum(upload), sum(register)  FROM `stat_day_paike` WHERE pid='a8c022bcd2adcbee' and date>= '{0}' and date < '{1}' group by date".format(st_datestr, et_datestr)
        print sql
        c.execute(sql)  
        res= c.fetchall()
        _tmpdate = ''
        for x in res:
            date = str(x[0])
            os = os_json.get(int(x[1])) or 'null'
            type1 = pidtype_json.get(int(x[2])) or 'null'
            pv = int(x[3])
            uv = int(x[4])
            vv = int(x[5])
            nu = int(x[6])
            su = int(x[7])
            nr = int(x[8])
            
            if _tmpdate and _tmpdate != date:
                results['data'] = os_data
                results['year'] = _tmpdate[:4]
                results['month'] = _tmpdate[4:6]
                results['day'] = _tmpdate[6:]
                all_data.append(results)
                results = {}
                os_data = []
            
            os_data.insert(0,{'os':os, 'type':type1, 'pv':pv, 'uv':uv, 'vv':vv, 'nr':nr, 'su':su, 'nu':nu})
            _tmpdate = date
        
        if len(os_data) > 0 :
            results['data'] = os_data
            results['year'] = _tmpdate[:4]
            results['month'] = _tmpdate[4:6]
            results['day'] = _tmpdate[6:]
            all_data.append(results)
            results = {}
            os_data = []
        
        self.write({"items":all_data})
        self.finish()

class WapTotalUser(BaseHandler):
    def get(self): 
        os_json = clientcache.getOS()
        pidtype_json = clientcache.getPidType()
        
        os_data = []

        db = connectMySQL.connMySQL_stat()
        c=db.cursor()
        sql = "SELECT date, os_id, pid_type, alluser  FROM `stat_day_paike` group by os_id order by alluser desc"
        print sql
        c.execute(sql)  
        res= c.fetchall()
        for x in res:
            os = os_json.get(int(x[1])) or 'null'
            type1 = pidtype_json.get(int(x[2])) or 'null'
            tu = int(x[3])
            os_data.insert(0,{'os':os, 'type':type1, 'tu':tu})

        self.write({"items":os_data})
        self.finish()
